package com.dsdl.chatapp.common.utils;

import android.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * Created by zzg on 2016/8/25.
 */
public class AESKey {
    private static final String AESKEY = "mingkunadmin1234";
    private static final String AESTYPE = "AES/CBC/PKCS5Padding";
    private static final String AESIV = "0102030102030102";
    /**
     * 加密
     * @param strKey
     * @return
     * @throws Exception
     */
    public static String encrypt(String strKey){
        try {
            SecretKeySpec skeySpec = getKey(AESKEY);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            IvParameterSpec iv = new IvParameterSpec(AESIV.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(strKey.getBytes());
            return Base64.encodeToString(encrypted, Base64.DEFAULT);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     * @param strKey
     * @return
     * @throws Exception
     */
    public static String decrypt(String strKey){
        try {
            SecretKeySpec skeySpec = getKey(AESKEY);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            IvParameterSpec iv = new IvParameterSpec(AESIV.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.decode(strKey, Base64.DEFAULT);

            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original,"utf-8");
            return originalString;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public static SecretKeySpec getKey(String strKey) throws Exception {
        byte[] arrBTmp = strKey.getBytes();
        byte[] arrB = new byte[16]; // 创建一个空的16位字节数组（默认值为0）

        for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {
            arrB[i] = arrBTmp[i];
        }

        SecretKeySpec skeySpec = new SecretKeySpec(arrB, "AES");

        return skeySpec;
    }

}
